<template>
   <!-- 弹窗组件 -->
   <div class="dialog-box">
      <el-dialog
         v-model="dialogVisible"
         title="采购订单审核"
         width="900"
      >
         <el-form label-width="100px">
            <div class="order-list">
               <div class="order-list-item">
                  <div class="order-list-item-label">采购单号</div>
                  <div class="order-list-item-value">
                     {{ props.orderList && props.orderList.length > 0 ? props.orderList[0].order_no : "" }}
                  </div>
               </div>
               <div class="order-list-item">
                  <div class="order-list-item-label">采购金额(元)</div>
                  <div class="order-list-item-value">
                     {{ props.orderList && props.orderList.length > 0 ? props.orderList[0].total_amount : "" }}
                  </div>
               </div>
               <div class="order-list-item">
                  <div class="order-list-item-label">采购日期</div>
                  <div class="order-list-item-value">
                     {{ props.orderList && props.orderList.length > 0 ? props.orderList[0].purchase_date : "" }}
                  </div>
               </div>
               <!-- <div class="order-list-item">
                  <div class="order-list-item-label">供应商</div>
                  <div class="order-list-item-value">
                     {{ props.orderList && props.orderList.length > 0 ? props.orderList[0].supplier_name : '' }}
                  </div>
               </div> -->
               <div class="order-list-item">
                  <div class="order-list-item-label">备注</div>
                  <div class="order-list-item-value order-list-item-value-note">
                     {{ props.orderList && props.orderList.length > 0 && props.orderList[0].note ? props.orderList[0].note : " --" }}
                  </div>
               </div>
               <div class="order-list-item">
                  <div class="order-list-item-label">提交人</div>
                  <div class="order-list-item-value">
                     {{ props.orderList && props.orderList.length > 0 ? props.orderList[0].creator_name : "" }}
                  </div>
               </div>
               <div class="order-list-item">
                  <div class="order-list-item-label">提交时间</div>
                  <div class="order-list-item-value">
                     {{ props.orderList && props.orderList.length > 0 ? props.orderList[0].created_at : "" }}
                  </div>
               </div>
            </div>
            <div class="supply-products">
               <div class="title">
                  <div class="title-text">
                     <div class="line"></div>
                     采购产品
                  </div>
               </div>
               <el-table
                  border
                  :data="orderDetail?.purchase_order_item"
                  style="width: 100%"
               >
                  <el-table-column
                     prop="product_name"
                     label="产品名称"
                     width="160"
                  />
                  <el-table-column
                     prop="specification"
                     label="规格型号"
                     width="160"
                  >
                     <template #default="scope">{{ scope.row.unit_num + scope.row.specification }}</template>
                  </el-table-column>
                  <el-table-column
                     prop="measure_unit_name"
                     label="采购单位"
                     width="160"
                  />
                  <el-table-column
                     prop="num"
                     label="采购数量"
                     width="160"
                  >
                     <template #default="scope">
                        {{ Math.floor(scope.row.num) }}
                     </template>
                  </el-table-column>
                  <el-table-column
                     prop="price"
                     label="采购单价(元)"
                     width="160"
                  >
                  </el-table-column>

                  <el-table-column
                     prop="open_unit_name"
                     label="拆零"
                     width="160"
                  >
                  </el-table-column>
                  <el-table-column
                     prop="total_price"
                     label="采购金额(元)"
                     width="160"
                  >
                     <template #default="scope">
                        {{ scope.row.total_price ? scope.row.total_price : "0" }}
                     </template>
                  </el-table-column>
                  <!-- <el-table-column
                     prop="final_price"
                     label="最终成交价(元)"
                     width="160"
                  >
                     <template #default="scope">
                        {{ scope.row.final_price ? scope.row.final_price : "0" }}
                     </template>
                  </el-table-column>  -->
               </el-table>
            </div>
            <div class="supply-products">
               <div class="title">
                  <div class="title-text">
                     <div class="line"></div>
                     价格设置
                  </div>
               </div>
               <el-row :gutter="20">
                  <el-col :span="12">
                     <el-form-item
                        label="整单折扣(%)"
                        type="number"
                     >
                        <el-input
                           disabled
                           @input="(value) => handleOrderDiscountChange(value)"
                           type="number"
                           v-model="orderDetail.order_discount"
                           placeholder="请输入"
                           min="0"
                           max="100"
                        />
                     </el-form-item>
                  </el-col>
                  <el-col :span="12">
                     <el-form-item label="整单成交额(元)">
                        <el-input
                           v-model="orderDetail.total_amount"
                           placeholder="请输入"
                           disabled
                        />
                     </el-form-item>
                  </el-col>
               </el-row>
               <el-form-item label="审核意见">
                  <el-input
                     v-model="form.audit_note"
                     placeholder="请输入"
                  />
               </el-form-item>
            </div>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button @click="dialogVisible = false">取消</el-button>
               <el-button
                  color="#626aef"
                  @click="handleSubmit('STATUS_3')"
               >
                  审核拒绝
               </el-button>
               <el-button
                  color="#626aef"
                  @click="handleSubmit('STATUS_2')"
               >
                  审核通过
               </el-button>
            </div>
         </template>
      </el-dialog>
   </div>
</template>

<script setup lang="ts">
   import { ref, reactive, watch, defineEmits, defineProps } from "vue";
   import { ElMessage } from "element-plus";
   import { ProcurementDetail, ProcurementItem } from "../procurementType.ts";
   import api from "@/api/index.js";
   import dayjs from "dayjs";
   const dialogVisible = ref<boolean>(false); // 弹窗控制器
   const emit = defineEmits(["refreshList"]);
   const props = defineProps({
      orderList: {
         type: Array as PropType<ProcurementDetail[]>,
         required: true,
      },
   });
   const form = ref<{ id: number; status: string; audit_note: string }>({
      id: 0,
      status: "",
      audit_note: "",
   });
   // 订单详情
   const orderDetail = ref<ProcurementDetail>({
      id: 0, // 订单id
      order_no: "", // 订单编号
      total_amount: 0,
      purchase_date: new Date(),
      create_time: "",
      supplier_id: "", // 供应商id
      supplier_name: "", // 供应商名称
      manager_member_id: 0, // 采购负责人id
      manager_name: "", // 采购负责人名称
      manager_phone: 0, // 采购负责人电话
      status: 0, // 状态
      pur_state: 0, // 采购状态
      note: "", // 备注
      creator_name: "", // 创建人
      audit_name: "", // 审核人
      audit_note: "", // 审核备注
      audited_at: new Date(), // 审核时间
      created_at: new Date(), // 创建时间
      status_note: "", // 状态备注
      order_discount: 0, // 整单折扣
      specification: "", // 规格型号
      purchase_order_item: [],
      total_price: 0,
   });
   const orderId = ref<number>();
   // 获取订单详情
   const getOrderDetail = async (id: number) => {
      const res = await api.procurement.purchaseOrderDetail({ id: id });
      if (res.code == 200) {
         orderDetail.value = res.data;
         // 确保整单折扣有默认值
         if (!orderDetail.value.order_discount) {
            orderDetail.value.order_discount = 100;
         }
         // calculateTotalAmount(); // 获取数据后计算总金额
      }
   };

   const openLoading = (id?: number) => {
      dialogVisible.value = true;
      orderId.value = id;
      if (id) {
         getOrderDetail(id);
      } else {
         orderDetail.value = {
            purchase_order_item: [],
         } as unknown as ProcurementDetail;
      }
      // 重置审核表单
      form.value = {
         id: id || 0,
         status: "",
         audit_note: "",
      };
   };
   interface PurchaseGoods {
      no: string;
      num: number;
      unit_price: number;
      discount: number;
   }
   interface PurchaseOrderParams {
      supplier_id: number;
      manager_member_id: number;
      purchase_date: string;
      note: string;
      purchase_goods: PurchaseGoods[];
      order_discount: number;
   }

   const handleSubmit = async (status: string) => {
      // 审核
      if (!orderId.value) {
         ElMessage.warning("请选择订单");
         return;
      }
      const res = await api.procurement.purchaseOrderAudit({
         id: orderId.value,
         status: status,
         audit_note: form.value.audit_note,
      });
      if (res.code == 200) {
         ElMessage.success(status == "STATUS_3" ? "审核拒绝" : "审核通过");
         dialogVisible.value = false;
         // 使用setTimeout确保对话框关闭后再触发刷新
         setTimeout(() => {
            emit("refreshList");
         }, 100);
      } else {
         ElMessage.error(res.message);
         dialogVisible.value = false;
      }
   };

   interface Supplier {
      Sname: string;
      name: string;
      Sphone: string;
      Sposition: string;
      id: number;
   }

   // 移除产品
   const handleRemoveProduct = (id: number) => {
      console.log(id);
      orderDetail.value.purchase_order_item = orderDetail.value.purchase_order_item.filter((item: ProcurementItem) => item.id !== id);
   };
   interface PurchaseOrderItem {
      spu_name: string;
      specification: string;
      unit: string;
      num: number;
      unit_price: number;
      discount: number;
      discount_price: number;
      final_price: number;
   }

   // // 格式化数字为两位小数
   // const formatNumber = (num: number): number => {
   //    return Math.max(0, Number(num.toFixed(2)));
   // };

   // // 验证输入是否为正数
   // const validatePositiveNumber = (value: string | number): number => {
   //    const num = Number(value);
   //    return num < 0 ? 0 : num;
   // };

   // // 监听单个产品的数量、单价和折扣变化
   // const calculateItemPrices = (item: PurchaseOrderItem) => {
   //    // 确保输入值非负
   //    const unitPrice = validatePositiveNumber(item.unit_price);
   //    const discount = validatePositiveNumber(item.discount);
   //    const num = validatePositiveNumber(item.num);

   //    // 计算折后价 = 单价 * 折扣
   //    item.discount_price = formatNumber(unitPrice * (discount / 100));
   //    // 计算最终成交价 = 折后价 * 数量
   //    item.final_price = formatNumber(item.discount_price * num);
   // };

   // // 计算整单成交额
   // const calculateTotalAmount = () => {
   //    if (!orderDetail.value.purchase_order_item?.length) return;

   //    // 计算所有产品的最终成交价总和
   //    const totalBeforeDiscount = orderDetail.value.purchase_order_item.reduce((sum, item) => {
   //       return sum + (Number(item.price) * Number(item.num) || 0);
   //    }, 0);

   //    // 应用整单折扣
   //    const orderDiscount = validatePositiveNumber(orderDetail.value.order_discount) || 100;
   //    orderDetail.value.total_amount = formatNumber(totalBeforeDiscount * (orderDiscount / 100));
   // };

   // // 监听产品列表变化
   // watch(
   //    () => orderDetail.value.purchase_order_item,
   //    (newItems) => {
   //       if (!newItems?.length) return;
   //       newItems.forEach((item) => {
   //          calculateItemPrices(item as unknown as PurchaseOrderItem);
   //       });
   //       calculateTotalAmount();
   //    },
   //    { deep: true }
   // );

   // // 监听整单折扣变化
   // watch(
   //    () => orderDetail.value.order_discount,
   //    () => {
   //       calculateTotalAmount();
   //    }
   // );

   // 处理输入值变化
   const handleInputChange = (value: string, row: any, field: string) => {
      if (value === "") {
         row[field] = 0;
         return;
      }

      let num = Number(value);

      // 确保数值不小于0
      if (num < 0) {
         num = 0;
      }

      // 如果是折扣，确保不超过100
      if (field === "discount" && num > 100) {
         num = 100;
      }

      row[field] = num;
   };

   // 处理整单折扣变化
   const handleOrderDiscountChange = (value: string) => {
      if (value === "") {
         orderDetail.value.order_discount = 100;
         return;
      }

      let num = Number(value);

      // 确保数值在0-100之间
      if (num < 0) {
         num = 0;
      } else if (num > 100) {
         num = 100;
      }

      orderDetail.value.order_discount = num;
      // 触发重新计算总金额
      // calculateTotalAmount();
   };

   defineExpose({
      openLoading,
   });
</script>

<style lang="scss" scoped>
   ::v-deep .el-dialog {
      --el-dialog-padding-primary: 0px;
   }
   ::v-deep .el-dialog__header {
      padding: 10px 16px;
      border-bottom: 1px solid #f0f0f0;
      font-weight: bold;
   }
   ::v-deep .dialog-footer {
      padding: 10px 16px;
      border-top: 1px solid #f0f0f0;
   }
   ::v-deep .el-dialog__headerbtn .el-dialog__close {
      color: #000;
   }
   ::v-deep .el-dialog__body {
      padding: 10px 10px;
   }
   :deep(.el-form-item__label) {
      justify-content: flex-start;
   }
   :deep(.el-form-item) {
      flex-direction: column;
      margin-bottom: 7px;
   }
   :deep(.el-select__wrapper) {
      background: #fafcfb;
   }
   :deep(.el-badge__content.is-fixed) {
      color: #666;
      border-radius: 3px;
      padding: 4px;
   }
   :deep(.el-table .cell) {
      display: flex;
      justify-content: center;
   }
   :deep(.el-button:hover) {
      color: #6860ff;
      background: #f4f5f7;
   }
   :deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
      width: 100%;
   }
   :deep(.el-input__wrapper:hover) {
      box-shadow: inset 0 0 0 1px #6860ff;
   }
   .supply-products {
      margin-top: 20px;
      .title {
         display: flex;
         align-items: center;
         justify-content: space-between;
         margin-bottom: 10px;
         font-weight: bold;
         .title-text {
            display: flex;
            align-items: center;
            .line {
               height: 17px;
               width: 2px;
               border-radius: 12px;
               margin-right: 8px;
               background-color: #6860ff;
            }
         }
      }
   }
   .order-list {
      display: flex;
      justify-content: space-around;
      padding: 15px 0;
      background: #f4f5f7;
      .order-list-item {
         .order-list-item-label {
            color: #666;
            margin-bottom: 5px;
         }
         .order-list-item-value {
            color: #1a1a1a;
         }
         .order-list-item-value-note {
            display: -webkit-box;
            width: 60px;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 1;
            overflow: hidden;
            text-overflow: ellipsis;
         }
      }
   }
   .image-list {
      display: flex;
      gap: 8px;
      .el-image {
         width: 40px;
         height: 40px;
         border-radius: 4px;
      }
   }
</style>
